//
//  Emoticon.swift
//  表情键盘
//
//  Created by 郝俊聪 on 15/5/24.
//  Copyright (c) 2015年 heima. All rights reserved.
//

import UIKit

class Emoticon: NSObject {
    
    var emoticon_group_name : String?
    var emoticon_group_path : String?
    var chs : String?
    var png : String?
    var code : String?{
        didSet{
            // scanner 是专门用来扫描字符串的
            let scanner = NSScanner(string: code!)
            // 扫描其中的16进制数字
            // 提示：scanner 的扫描结果会输出到 result，不能使用 let
            var result: UInt32 = 0
            scanner.scanHexInt(&result)
            emojiStr = "\(Character(UnicodeScalar(result)))"
        }
    }
    var isDelete = false
    var isEmpty = false
    var emojiStr : String?
    
    ///返回所有的emotican对象
    class func allEmoticonsFromPlist()->[Emoticon]{
         //获得emoticons.plist路径
        let path = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Emoticons.bundle").stringByAppendingPathComponent("emoticons.plist")
        let array = NSArray(contentsOfFile: path) as! [[String:String]]
        //创建一个数组，装[emoticon]数组
        var arrayM = [Emoticon]()
        //遍历数组
        for dict in array{
            let emoticon_group_path = dict["emoticon_group_path"]
            //调用emoticonsWith方法获得[Emoticon]数组
            let arrayEmo = emoticonsWith(emoticon_group_path!)
            //装入数组中
            arrayM += arrayEmo
        }
        return arrayM
    }
    
    ///将带表情符号文字转化为带emoticon图片的属性文字
    class func emoticonString(string:String,lineHeight:CGFloat)->NSAttributedString{
        //利用正则表达式过滤表情符号([]是正则表达式中的保留字，不能直接使用，如果要用，需要使用\\转译)
        //1.匹配方案
        let pattern = "\\[.*?\\]"
        //2.正则表达式
        let regex = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators, error: nil)
        
        //3.开始匹配，并替换文字
        //根据字符串，创建一个可变的属性文本
        var strM = NSMutableAttributedString(string: string)
        //判断是否找到匹配项
        if let results = regex?.matchesInString(string, options: NSMatchingOptions(0), range: NSMakeRange(0, count(string))){
            //从后面开始遍历匹配的结果（从后面替换字符串，不会影响前面字符串的range）
            var index = results.count - 1
            while index >= 0{
                let r = results[index--] as! NSTextCheckingResult
                let range = r.rangeAtIndex(0)
                //抓出emoticon.chs
                let emoticonStr = (string as NSString).substringWithRange(range)
                //使用过滤器过滤出emoticon对象
                let emoticon = emoticons.filter{$0.chs == emoticonStr}.last
                
                //判断是否找到表情对象
                if emoticon != nil{
                   //创建附件
                   let attr = NSTextAttachment()
                   attr.image = UIImage(contentsOfFile: emoticon!.png!)
                   attr.bounds = CGRectMake(0,0, lineHeight, lineHeight)
                   //装成属性文本
                   let attrString = NSAttributedString(attachment: attr)
                   //替换
                   strM.replaceCharactersInRange(range, withAttributedString: attrString)
                
                }
            }
        }
        
        //返回
        return strM
    }
    
    ///定义一个常量。记录所有的emticons
    static let emoticons = Emoticon.allEmoticonsFromPlist()
    
    ///根据emoticon_group_path返回emoticon数组
    class func emoticonsWith(emoticon_group_path:String)->[Emoticon]{
        
        let dirPath = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Emoticons.bundle").stringByAppendingPathComponent(emoticon_group_path)
        let infoPath = dirPath.stringByAppendingPathComponent("info.plist")
        let dict = NSDictionary(contentsOfFile: infoPath)
        let array = dict!["emoticon_group_emoticons"] as! [[String:String]]
        //创建临时数组，装emotican对象
        var arrayM = [Emoticon]()
        //遍历数组创建对象
        var index = 0
        for dict in array{
            //创建对象
            let emoticon = Emoticon()
            if emoticon_group_path == "emoji"{
                emoticon.code = dict["code"]
            }else{
                emoticon.chs = dict["chs"]
                if dict["png"] != nil{
                    emoticon.png = dirPath.stringByAppendingPathComponent(dict["png"]!)
                }
            }
            //装入临时数组
            arrayM.append(emoticon)
            index++
            //第21个空出一个位置,做删除按钮
            if index%20 == 0 {
                let emoticon = Emoticon()
                emoticon.isDelete = true
                arrayM.append(emoticon)
            }
        }
        //当某一页不足20的时候，用空按钮补齐
        for _ in  0 ... (20 - array.count % 20){
            let emoticon = Emoticon()
            emoticon.isEmpty = true
            arrayM.append(emoticon)
        }
        //返回
        return arrayM
    }
    
}
